{% extends 'admin/common/base.html' %}
{% block css %}
{{super()}}
<link href="{{url_for('admin.static',filename='ajax/libs/jquery-layout/jquery.layout-latest.css')}}" rel="stylesheet" />
<link href="{{url_for('admin.static',filename='ajax/libs/jquery-ztree/3.5/css/metro/zTreeStyle.css')}}"
    rel="stylesheet" />
{% endblock %}
{% block body %}

<body class="gray-bg">
    <div class="ui-layout-west">
        <div class="box box-main">
            <div class="box-header">
                <div class="box-title">
                    <i class="fa icon-grid"></i> 文章分类
                </div>
                <div class="box-tools pull-right">
                    <a type="button" class="btn btn-box-tool" href="#" onclick="open_category()" title="管理部门"><i
                            class="fa fa-edit"></i></a>
                    <button type="button" class="btn btn-box-tool" id="btnExpand" title="展开" style="display:none;"><i
                            class="fa fa-chevron-up"></i></button>
                    <button type="button" class="btn btn-box-tool" id="btnCollapse" title="折叠"><i
                            class="fa fa-chevron-down"></i></button>
                    <button type="button" class="btn btn-box-tool" id="btnRefresh" title="刷新部门"><i
                            class="fa fa-refresh"></i></button>
                </div>
            </div>
            <div class="ui-layout-center">
                <div class="ui-layout-content">
                    <div id="tree" class="ztree"></div>
                </div>
            </div>
        </div>
    </div>
    <div class="ui-layout-center">
        <div class="container-div">
            <div class="row">
                <div class="col-sm-12 search-collapse">
                    <form id="role-form">
                        <input type="hidden" id="category_id" name="category_id">
                        <div class="select-list">
                            <ul>
                                <li>
                                    标题：<input type="text" name="title" />
                                </li>
                                <li>
                                    <label>状态：</label>
                                    <select name="state">
                                        <option value="">所有</option>
                                        {% for dd in get_dict_data('cms_article_state')%}
                                        <option value="{{dd.value}}">{{dd.label}}</option>
                                        {% endfor %}
                                    </select>
                                </li>
                                <li class="select-time">
                                    <label>发布时间：</label>
                                    <input type="text" class="time-input" id="startTime" placeholder="开始时间"
                                        name="publish_time_start" />
                                    <span>-</span>
                                    <input type="text" class="time-input" id="endTime" placeholder="结束时间"
                                        name="publish_time_end" />
                                </li>
                                <li>
                                    <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i
                                            class="fa fa-search"></i>&nbsp;搜索</a>
                                    <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i
                                            class="fa fa-refresh"></i>&nbsp;重置</a>
                                </li>
                            </ul>
                        </div>
                    </form>
                </div>

                <div class="btn-group-sm" id="toolbar" role="group">
                    <a class="btn btn-success {{check_perms('cms:article:add')}}"
                        onclick="$.operate.addTab($('#category_id').val())">
                        <i class="fa fa-plus"></i> 新增
                    </a>
                    <a class="btn btn-primary single disabled {{check_perms('cms:article:edit')}}"
                        onclick="$.operate.editTab()">
                        <i class="fa fa-edit"></i> 修改
                    </a>
                    <a class="btn btn-danger multiple disabled {{check_perms('cms:article:remove')}}"
                        onclick="$.operate.removeAll()">
                        <i class="fa fa-remove"></i> 删除
                    </a>
                    <a class="btn btn-warning multiple disabled {{check_perms('cms:article:edit')}}"
                        onclick="change_category()">
                        <i class="fa fa-remove"></i> 移动目录
                    </a>
                </div>

                <div class="col-sm-12 select-table table-striped">
                    <table id="bootstrap-table" data-use-row-attr-func="true" data-reorderable-rows="true"></table>
                </div>
            </div>
        </div>
    </div>
</body>
{% endblock %}
{% block js %}
{{ super() }}
<script src="{{url_for('admin.static',filename='ajax/libs/jquery-layout/jquery.layout-latest.js')}}"></script>
<script src="{{url_for('admin.static',filename='ajax/libs/jquery-ztree/3.5/js/jquery.ztree.all-3.5.js')}}"></script>
<script
    src="{{url_for('admin.static',filename='ajax/libs/bootstrap-table/extensions/reorder-rows/bootstrap-table-reorder-rows.js')}}"></script>
<!-- <script
    src="{{url_for('admin.static',filename='ajax/libs/bootstrap-table/extensions/reorder/bootstrap-table-reorder.js')}}"></script> -->
<script
    src="{{url_for('admin.static',filename='ajax/libs/bootstrap-table/extensions/reorder-rows/jquery.tablednd.js')}}"></script>
<script
    src="{{url_for('admin.static',filename='ajax/libs/bootstrap-table/extensions/editable/bootstrap-editable.min.js')}}"></script>
<script
    src="{{url_for('admin.static',filename='ajax/libs/bootstrap-table/extensions/editable/bootstrap-table-editable.min.js')}}"></script>
<script>
    var editFlag = "{{check_perms('cms:article:edit')}}";
    var removeFlag = "{{check_perms('cms:article:remove')}}";
    var state_datas = {{ get_dict_data('cms_article_state') | tojson | safe}};
    $(function () {
        var panehHidden = false;
        if ($(this).width() < 769) {
            panehHidden = true;
        }
        $('body').layout({ initClosed: panehHidden, west__size: 185 });
        // 回到顶部绑定
        if ($.fn.toTop !== undefined) {
            var opt = {
                win: $('.ui-layout-center'),
                doc: $('.ui-layout-center')
            };
            $('#scroll-up').toTop(opt);
        }
        queryList();
        queryCategoryTree();

    });

    //随机整数
    function getRandom(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    var dragbeforeidx;//开始
    var draglateridx;//开始
    function queryList() {
        var options = {
            url: "{{url_for('admin.cms.article.list')}}",
            createUrl: "{{url_for('admin.cms.article.edit')}}?category_id={id}",
            updateUrl: "{{url_for('admin.cms.article.edit')}}?id={id}",
            removeUrl: "{{url_for('admin.cms.article.remove')}}",
            exportUrl: "{{url_for('admin.cms.article.export')}}",
            modalName: "文章",
            onEditableSave: onEditableSave,
            // reorderableRows: true,
            useRowAttrFunc: true, //设置拖动排序
            //当选中行，拖拽时的哪行数据，并且可以获取这行数据的上一行数据和下一行数据             
            onReorderRowsDrag: function (row) {
                // console.log(row.id)
                // console.log(row)
                //取索引号
                // dragbeforeidx = $(row).attr("data-index");
                dragbeforeidx = row.id;
            },
            //拖拽完成后的这条数据，并且可以获取这行数据的上一行数据和下一行数据
            onReorderRowsDrop: function (row) {
                //取索引号
                // console.log(row)
                draglateridx = row.id
                // console.log(dragbeforeidx,row.id);
                // change_sn(dragbeforeidx, draglateridx);
            },
            onReorderRow: function (data, newRow, oldRow, el) {
                // 当拖拽结束后，data为整个表格的数据
                // console.table(data)
                // console.log(newRow, oldRow)

                let index = 0;
                for (let i = 0; i < data.length; i++) {
                    if (data[i].id == dragbeforeidx) {
                        index = i;
                        break
                    }
                }
                let sn = 0;
                if (index == 0) {
                    sn = parseInt(data[index + 1].sn) + 1
                } else if (index == data.length - 1) {
                    sn = parseInt(data[index - 1].sn) - 1
                } else {
                    let max = parseInt(data[index - 1].sn)
                    let min = parseInt(data[index + 1].sn)
                    sn = getRandom(min, max)
                    // console.log(min, max, sn)
                }

                change_sn(dragbeforeidx, sn)

                // console.log(sn)


                // 当sidePagination: "server"时，拖拽行后顺序错乱，需要重新调用加载数据方法
                // $("#" + table.options.id).bootstrapTable('load', {
                //     total: el._xhr.responseJSON.total,
                //     rows: data
                // });

                return false;
            },
            columns: [
                {
                    checkbox: true
                },
                {
                    field: 'id',
                    title: 'ID',
                    visible: true
                },
                {
                    field: 'title',
                    title: '标题',
                    formatter: function (value, row, index) {
                        return $.table.tooltip(value, 30, "open");
                    }
                },
                {
                    field: 'name',
                    title: '编码'
                },
                {
                    field: 'category.title',
                    title: '栏目'
                },
                {
                    field: 'summary',
                    title: '概述',
                    visible: false,
                    formatter: function (value, row, index) {
                        return $.table.tooltip(value, 10, "open");
                    }
                },
                {
                    field: 'author',
                    title: '作者',
                },
                {
                    field: 'ctime',
                    title: '创建时间',
                    visible:false,
                },
                {
                    title: '发布状态',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return statusTools(row);
                    }
                },
                {
                    field: 'publish_time',
                    title: '发布时间'
                },
                {
                    field: 'sn',
                    title: '排序',
                    editable: {
                        type: 'number',
                        title: '排序'
                    }
                },
                {
                    title: '预览',
                    align: 'center',
                    formatter: function (value, row, index) {
                        let html = "<a href='/article/" + row.name + "?preview=yes' target='_blank'><i class='fa fa-external-link fa-fw'></i>预览</a>"
                        return html;
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="$.operate.editTab(\'' + row.id + '\')"><i class="fa fa-edit"></i>编辑</a> ');
                        actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.id + '\')"><i class="fa fa-remove"></i>删除</a> ');
                        return actions.join('');
                    }
                }]
        };
        $.table.init(options);
    }

    function queryCategoryTree() {
        var url = "{{url_for('admin.cms.category.category_tree_data')}}";
        var options = {
            url: url,
            expandLevel: 1,
            onClick: zOnClick,
            data: {
                key: {
                    name: 'title',
                    title: "title",
                    url: ''
                },
                simpleData: {
                    enable: true,
                    pIdKey: "parent_id",

                }
            }
        };
        $.tree.init(options);

        function zOnClick(event, treeId, treeNode) {
            var treeId = treeNode.id;
            var treeName = treeNode.title;
            $("#category_id").val(treeId);
            $("#treeName").val(treeName);
            $.table.search();
        }
    }

    $('#btnExpand').click(function () {
        $._tree.expandAll(true);
        $(this).hide();
        $('#btnCollapse').show();
    });

    $('#btnCollapse').click(function () {
        $._tree.expandAll(false);
        $(this).hide();
        $('#btnExpand').show();
    });

    $('#btnRefresh').click(function () {
        queryCategoryTree();
    });
    function open_category() {
        var url = "{{url_for('admin.cms.category.index')}}";
        $.modal.openTab("栏目管理", url);
    }

    /* 用户状态显示 */
    function statusTools(row) {
        // console.log(row)
        if (row.state == 1) {
            return '<i class=\"fa fa-toggle-on text-info fa-2x\" onclick="disable(\'' + row.id + '\')"></i> ';
        } else {
            return '<i class=\"fa fa-toggle-off text-info fa-2x\" onclick="enable(\'' + row.id + '\')"></i> ';
        }
    }
    /* 操作 */
    function disable(id) {
        $.modal.confirm("确认要取消发布吗？", function () {
            $.operate.post("{{url_for('admin.cms.article.change_state')}}", { "id": id, "state": 0 });
        })
    }

    /* 发布 */
    function enable(id) {
        $.modal.confirm("确认要发布吗？", function () {
            $.operate.post("{{url_for('admin.cms.article.change_state')}}", { "id": id, "state": 1 });
        })
    }
    /*排序*/
    function change_sn(id, sn) {
        let data = { id: id, sn: sn };
        $.operate.post("{{url_for('admin.cms.article.change_sn')}}", data);
    }
    function onEditableSave(field, row, rowIndex, oldValue, $el) {
        // alert("字段名：" + field + "，当前值：" + row[field]  + "，旧值：" + oldValue);
        if (field == 'sn') {
            let data = { id: row.id, sn: row[field] };
            $.operate.post("{{url_for('admin.cms.article.change_sn')}}", data);
        }
    }

    /*新增-选择上级*/
    function selectTree() {
        var treeId = $("#treeId").val();
        var menuId = treeId > 0 ? treeId : 1;
        var url = "{{url_for('admin.cms.category.select_tree')}}?id=" + menuId;
        var options = {
            title: '选择',
            width: "380",
            url: url,
            callBack: doSubmit
        };
        $.modal.openOptions(options);
    }

    var ids = '';
    function doSubmit(index, layero) {
        var body = $.modal.getChildFrame(index);
        let category_id = body.find('#treeId').val();
        $.operate.post("{{url_for('admin.cms.article.change_category')}}", { "ids": ids, "category_id": category_id });
        $.modal.close(index);
    }

    //移动目录
    function change_category() {
        table.set();
        var rows = $.common.isEmpty(table.options.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns(table.options.uniqueId);
        if (rows.length == 0) {
            $.modal.alertWarning("请至少选择一条记录");
            return;
        }
        ids = rows.join();
        selectTree();
    }
</script>
{% endblock %}